#include <iostream>
#include "mutex.hpp"
#include "Thread.hpp"

pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
int tickets = 1000;

void *getTickets(void *args)
{
    std::string name = static_cast<const char *>(args);

    while (true)
    {
        // 使用大花括号，出作用域之后lockguard调用析构函数自动解锁
        {
            LockGuard lockguard(&lock); // 初始化的时候自动加锁
            if (tickets > 0)
            {
                usleep(1000);
                std::cout << name << "获取火车票,该票票号为:" << tickets-- << std::endl;
            }
            else
            {
                std::cout << "无票可抢" << std::endl;
                break;
            }
        }
    }

    usleep(1000);
    return 0;
}

int main()
{
    Thread *thread1 = new Thread(getTickets, (void *)"thread 1", 0);
    Thread *thread2 = new Thread(getTickets, (void *)"thread 2", 0);
    Thread *thread3 = new Thread(getTickets, (void *)"thread 3", 0);
    Thread *thread4 = new Thread(getTickets, (void *)"thread 4", 0);

    thread1->start();
    thread2->start();
    thread3->start();
    thread4->start();

    thread1->join();
    thread2->join();
    thread3->join();
    thread4->join();

    // 主线程
    while (true)
    {
        std::cout << "我是主线程" << std::endl;
        sleep(1);
    }
    return 0;
}